#include <Connectivity/TCPClient.hpp>

TCPClient::TCPClient(bool ipv6) {

	this->ipv6 = ipv6;

}

TCPConnection *TCPClient::openConnection(int port, std::string &address) {

	int sock;
	struct sockaddr *server;
	size_t len;

	/* Configure socket depending in ip version */
	if (ipv6) {

		len = sizeof(struct sockaddr_in6);
		struct sockaddr_in6 *server_local = (struct sockaddr_in6*) malloc(len);

		/* Create IPv6 socket */
		sock = socket( AF_INET6, SOCK_STREAM, 0);
		if (sock < 0) {
			std::cerr << "Error: Socket" << std::endl;
			return 0;
		}

		/* Set adress, ip version and port */
		inet_pton(AF_INET6, address.c_str(), &(server_local->sin6_addr));
		server_local->sin6_family = AF_INET6;
		server_local->sin6_port = htons(port);

		server = (struct sockaddr*)server_local;

	} else {

		len = sizeof(struct sockaddr_in);
		struct sockaddr_in *server_local = (struct sockaddr_in*) malloc(len);

		/* Create IPv4 socket */
		sock = socket( AF_INET, SOCK_STREAM, 0);
		if (sock < 0) {
			std::cerr << "Error: Socket" << std::endl;
			return 0;
		}

		/* Set adress, ip version and port */
		inet_aton(address.c_str(), &(server_local->sin_addr));
		server_local->sin_family = AF_INET;
		server_local->sin_port = htons(port);

		server = (struct sockaddr*)server_local;

	}

	/* Connect to server and return a new TCP connection */
	if (connect(sock, server, len) < 0) {
		std::cerr << "Error: Connect" << std::endl;
		return 0;
	} else {
		return new TCPConnection(ipv6, sock, (struct sockaddr*)server);
	}
}

